#include "RegistrationInfo.h"

LIST_HEAD(user_Info_list);

// 添加挂号信息到链表
void add_registration(const char *card_number, const char *name,const char *department, const char *doctor,const char *time_slot)
{
    RegistrationInfo *new_node = malloc(sizeof(RegistrationInfo));
    if (!new_node)
    {
        printf("内存分配失败\n");
        return;
    }

    // 复制信息
    strncpy(new_node->card_number, card_number, sizeof(new_node->card_number) - 1);
    strncpy(new_node->name, name, sizeof(new_node->name) - 1);
    strncpy(new_node->department, department, sizeof(new_node->department) - 1);
    strncpy(new_node->doctor, doctor, sizeof(new_node->doctor) - 1);
    strncpy(new_node->time_slot, time_slot, sizeof(new_node->time_slot) - 1);

    // 初始化链表节点并添加到链表尾部
    INIT_LIST_HEAD(&new_node->list);
    list_add_tail(&new_node->list, &user_Info_list);
}

// 保存链表到文件
int write_registration_to_file(const char *card_number, 
                            const char *name,const char *department,
                             const char *doctor,const char *time_slot)
{
    FILE *file = fopen("/lvgl_yiyuan/RegistrationInfo.txt", "a+");
    // FILE *file = fopen("./RegistrationInfo.txt", "a+");
    if (!file)
    {
        perror("无法打开文件");
        return 0;
    }

    struct list_head *pos;
    RegistrationInfo *new_node;

    // 遍历链表并写入每个用户信息
    list_for_each(pos, &user_Info_list)
    {
        new_node = list_entry(pos, RegistrationInfo, list);
        fprintf(file, "就诊卡号:%s\n", card_number);
        fprintf(file, "患者姓名:%s\n", name);
        fprintf(file, "科室:%s\n", department);
        fprintf(file, "医生:%s\n", doctor);
        fprintf(file, "时段:%s\n", time_slot);
        fprintf(file, "-----------------\n");
    }

    fclose(file);
    return 1;
}

// 释放链表内存
void free_registration_list() 
{
    struct list_head *pos, *tmp;
    RegistrationInfo *new_node;
    
    list_for_each_safe(pos, tmp, &user_Info_list) {
        new_node = list_entry(pos, RegistrationInfo, list);
        list_del(pos);
        free(new_node);
    }
}